//
//  DiscoverMarketViewController.m
//  陶瓷
//
//  Created by 郭天龙 on 15/7/29.
//  Copyright (c) 2015年 王戈. All rights reserved.
//

#import "DiscoverMarketViewController.h"
#import "UIImageView+WebCache.h"
#import "TCNavigationItemFavouriteBtn.h"
#import "TCNetworkTool.h"
#import "MarketModel.h"
#import "TCMarkerBrandCell.h"

@interface DiscoverMarketViewController ()<BMKMapViewDelegate,BMKLocationServiceDelegate ,UITableViewDelegate ,UITableViewDataSource>

@property (nonatomic, weak) IBOutlet NSLayoutConstraint *layoutHeight;
@property (nonatomic, weak) IBOutlet UIScrollView *scrollview;
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@property (nonatomic, weak) IBOutlet UIView *nameView;
//@property (nonatomic, weak) IBOutlet UILabel *marketLabel1;
//@property (nonatomic, weak) IBOutlet UILabel *marketLabel3;
//@property (nonatomic, weak) IBOutlet UILabel *marketLabel4;
//@property (nonatomic, weak) IBOutlet UILabel *marketLabel6;
//@property (nonatomic, weak) IBOutlet UILabel *marketLabel7;
//@property (nonatomic, weak) IBOutlet UILabel *marketLabel9;
//@property (nonatomic, weak) IBOutlet UILabel *marketLabel10;
//@property (nonatomic, weak) IBOutlet UILabel *marketLabel12;
@property (nonatomic, weak) IBOutlet UILabel *addressLabel;
@property (nonatomic, weak) IBOutlet UILabel *browser;

@property (nonatomic, strong) MarketModel *model;
@property (nonatomic, strong) UIButton *favorBtn;
@property (nonatomic, strong) UIButton *cover;
@property (weak, nonatomic) IBOutlet UITableView *MarketBrandTableView;

@property (nonatomic, strong) BMKMapView *mapView;

@property (strong,nonatomic) BMKLocationService *locService;

@property (nonatomic, assign) CGFloat locaLatitude;
@property (nonatomic, assign) CGFloat locaLongitude;
@property (nonatomic, strong) NSArray *brandArray;


@end

@implementation DiscoverMarketViewController

#pragma mark - Action
- (IBAction)clickFindCompany:(id)sender
{
    //    TailMapViewController *mapvc = [[TailMapViewController alloc] init];
    //    [self.navigationController pushViewController:mapvc animated:YES];
    
    [self initBMKUserLocation];
}

- (IBAction)clickTel:(id)sender
{
    //    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",self.model]]];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.title = @"市场";
    
    [self setupNavigationItem];
    
    //百度地图创建
    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, self.addressLabel.frame.size.height+self.addressLabel.frame.origin.y+10, kDefaultWindowWidth, 100)];
    [_mapView setMapType:BMKMapTypeStandard];
    self.layoutHeight.constant = 360;
    
    [self.nameView addSubview:_mapView];
    
    _MarketBrandTableView.delegate = self;
    _MarketBrandTableView.dataSource = self;
    _MarketBrandTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _brandArray = [NSArray array];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self refreshVC];
    
    if(!IsLoginIn) {
        _favorBtn.hidden = YES;
    } else {
        if (!_isFavor && _favorBtn) {
            [[TCNetworkTool sharedNetTool] checkIsFavouritesWithType:kTCCollectTypeMarket andObjectID:_sid andSuccessBlocks:^(NSString *successMessage) {
                self.isFavor = [successMessage isEqualToString:@"已关注此信息"];
            } andFailureBlocks:^(NSString *failureMessage) {
                if ([failureMessage isEqualToString:@"未关注此信息"]) {
                    self.isFavor = NO;
                }
            }];
        } else {
            self.favorBtn.selected = YES;
        }
    }
}

- (void)mapDisable
{
    _mapView.zoomEnabled = NO;
    _mapView.zoomEnabledWithTap = NO;
    _mapView.scrollEnabled = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.cover removeFromSuperview];
    [SVProgressHUD dismiss];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
}

- (UIButton *)cover {
    if (_cover == nil) {
        _cover = [[UIButton alloc] initWithFrame:self.view.bounds];
        _cover.backgroundColor = [UIColor clearColor];
    }
    
    return _cover;
}

- (void)refreshVC
{
    [SVProgressHUD showWithStatus:@"正在获取市场详情 请稍后.."];
    [self.view addSubview:self.cover];
    TCNetworkTool *tctool = [TCNetworkTool sharedNetTool];
    [tctool MarketDetailWithID:self.sid andSuccessBlocks:^(id successMessage) {
        [SVProgressHUD dismiss];
        [self.cover removeFromSuperview];
        self.model = successMessage;
        self.browser.text = [NSString stringWithFormat:@"已有%ld人浏览",(long)self.model.BrowseNumber];
        self.title = self.model.Name;
        [self setupUI:_model];
        BMKPointAnnotation* annotation = [[BMKPointAnnotation alloc]init];
        CLLocationCoordinate2D coor;
        coor.latitude = [self.model.Latitude floatValue];
        coor.longitude = [self.model.Longitude floatValue];
        annotation.coordinate = coor;
        annotation.title = self.model.Address;
        [_mapView addAnnotation:annotation];
        [_mapView setCenterCoordinate:coor];
        _mapView.zoomLevel = 16;
        [self mapDisable];
    } andFailureBlocks:^(NSString *failureMessage) {
        [SVProgressHUD dismiss];
        [self.cover removeFromSuperview];
        [MBHUDHelper showWarningWithText:failureMessage];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupUI:(MarketModel *)markmodel
{
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:markmodel.HeadImageUrl] placeholderImage:nil];
    NSArray *brandArr = [markmodel.Brands componentsSeparatedByString:@"|"];
    _brandArray = nil;
    _brandArray = [brandArr copy];
    [_MarketBrandTableView reloadData];
    
    self.addressLabel.text = markmodel.Address;
    
    /*for (int i = 0; i<[brandArr count]; i++) {
        switch (i) {
            case 0:
            {
                self.marketLabel1.text = [brandArr objectAtIndex:i];
                self.marketLabel1.hidden = NO;
            }
                continue;
            case 1:
            {
                self.marketLabel3.text = [brandArr objectAtIndex:i];
                self.marketLabel3.hidden = NO;
            }
                continue;
            case 2:
            {
                self.marketLabel4.text = [brandArr objectAtIndex:i];
                self.marketLabel4.hidden = NO;
            }
                continue;
            case 3:
            {
                self.marketLabel6.text = [brandArr objectAtIndex:i];
                self.marketLabel6.hidden = NO;
            }
                continue;
            case 4:
            {
                self.marketLabel7.text = [brandArr objectAtIndex:i];
                self.marketLabel7.hidden = NO;
            }
                continue;
            case 5:
            {
                self.marketLabel9.text = [brandArr objectAtIndex:i];
                self.marketLabel9.hidden = NO;
            }
                continue;
            case 6:
            {
                self.marketLabel10.text = [brandArr objectAtIndex:i];
                self.marketLabel10.hidden = NO;
            }
                continue;
            case 7:
            {
                self.marketLabel12.text = [brandArr objectAtIndex:i];
                self.marketLabel12.hidden = NO;
            }
                continue;
                
            default:
                continue;
        }
    }*/
}

- (void)setupNavigationItem {
    _favorBtn = [TCNavigationItemFavouriteBtn favouriteBtn];
    [_favorBtn addTarget:self action:@selector(favourite) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_favorBtn];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    self.navigationController.navigationBar.translucent = NO;
}

// 收藏
- (void)favourite {
    [self.view addSubview:self.cover];
    [[TCNetworkTool sharedNetTool] addFavouritesWithId:nil andUserId:nil andCollectType:kTCCollectTypeMarket andTypeID:_sid andAddTime:nil andSuccessBlocks:^(NSString *successMessage) {
        self.isFavor = [successMessage isEqualToString:@"关注成功，可在我的关注中查看"];
        [self.cover removeFromSuperview];
    } andFailureBlocks:^(NSString *failureMessage) {
        [self.cover removeFromSuperview];
    }];
    
}

- (void)setIsFavor:(BOOL)isFavor {
    _isFavor = isFavor;
    _favorBtn.selected = isFavor;
}

#pragma mark - BMKMapViewDelegate
// Override
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.pinColor = BMKPinAnnotationColorPurple;
        newAnnotationView.animatesDrop = YES;// 设置该标注点动画显示
        return newAnnotationView;
    }
    return nil;
}

//- (IBAction)clickFindCompany:(id)sender
//{
//    //    TailMapViewController *mapvc = [[TailMapViewController alloc] init];
//    //    [self.navigationController pushViewController:mapvc animated:YES];
//
//    [self initBMKUserLocation];
//}
//
//- (IBAction)clickTel:(id)sender
//{
////    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",self.model.]]];
//}


#pragma mark - BMKLocationServiceDelegate
/**
 *  初始化百度地图用户位置管理类
 */
- (void)initBMKUserLocation
{
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    [self startLocation];
}

/**
 *  打开定位服务
 */
-(void)startLocation
{
    [_locService startUserLocationService];
}

/**
 *  关闭定位服务
 */
-(void)stopLocation
{
    [_locService stopUserLocationService];
}


//-(void)mapView:(BMKMapView *)mapView didUpdateUserLocation:(BMKUserLocation *)userLocation{
//    NSLog(@"latitude--%f,longtitude---%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
//    self.locaLatitude=userLocation.location.coordinate.latitude;//纬度
//    self.locaLongitude=userLocation.location.coordinate.longitude;//精度
//}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation;
{
    self.locaLatitude = userLocation.location.coordinate.latitude;
    self.locaLongitude = userLocation.location.coordinate.longitude;
    [self stopLocation];//(如果需要实时定位不用停止定位服务)
    [self mapViewWillStartLocatingUser:nil];
}

-(void)mapViewWillStartLocatingUser:(BMKMapView *)mapView{
    NSLog(@"开始定位");
    BMKOpenTransitRouteOption *opt = [[BMKOpenTransitRouteOption alloc] init];
    opt.appScheme = @"baidumapsdk://mapsdk.baidu.com";//用于调起成功后，返回原应用
    //初始化起点节点
    BMKPlanNode* start = [[BMKPlanNode alloc]init];
    //指定起点经纬度
    CLLocationCoordinate2D coor1;
    coor1.latitude = self.locaLatitude;
    coor1.longitude = self.locaLongitude;
    //指定起点名称
    start.name = @"我的位置";
    start.pt = coor1;
    //指定起点
    opt.startPoint = start;
    
    //初始化终点节点
    BMKPlanNode* end = [[BMKPlanNode alloc]init];
    CLLocationCoordinate2D coor2;
    coor2.latitude = [self.model.Latitude floatValue];
    coor2.longitude = [self.model.Longitude floatValue];
    end.pt = coor2;
    //指定终点名称
    end.name = self.model.Address;
    opt.endPoint = end;
    
    //打开地图公交路线检索
    BMKOpenErrorCode code = [BMKOpenRoute openBaiduMapTransitRoute:opt];
}

#pragma mark - table view datasource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    tableView.hidden = !_brandArray.count;
    return (_brandArray.count + 1) * 0.5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TCMarkerBrandCell *cell = [TCMarkerBrandCell cellWithTableView:tableView];
    cell.LeftBrandLabel.text = _brandArray[indexPath.row * 2];
    if (_brandArray.count > (indexPath.row * 2 +1)) {
        cell.RightBrandLabel.text = _brandArray[indexPath.row * 2 +1];
    }
    return cell;
}
@end
